Best Time to Buy and Sell Stock
LeetCode 121 | Difficulty: Easyβ
EasyProblem Descriptionβ
You are given an array prices where prices[i] is the price of a given stock on the i^th day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
- `1 <= prices.length <= 10^5`
- `0 <= prices[i] <= 10^4`
Topics: Array, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
When to use
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
Solutionsβ
Solution 1: C# (Best: 112 ms)β
| Metric | Value |
|---|---|
| Runtime | 112 ms |
| Memory | 23.1 MB |
| Date | 2019-02-20 |
Solution
public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length==0) return 0;
int minSoFar = prices[0];
int maxProfitSoFar = 0;
for (int i = 1; i < prices.Length; i++)
{
maxProfitSoFar = Math.Max(maxProfitSoFar, prices[i] - minSoFar);
minSoFar = Math.Min(prices[i], minSoFar);
}
return maxProfitSoFar;
}
}
π 2 more C# submission(s)
Submission (2019-02-20) β 180 ms, 26 MBβ
public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length==0) return 0;
int minSoFar = prices[0];
int maxProfitSoFar = 0;
for (int i = 1; i < prices.Length; i++)
{
maxProfitSoFar = Math.Max(maxProfitSoFar, prices[i] - minSoFar);
minSoFar = Math.Min(prices[i], minSoFar);
Console.WriteLine($"{prices[i]} {maxProfitSoFar} {minSoFar}");
}
return maxProfitSoFar<0 ? 0 : maxProfitSoFar;
}
}
Submission (2022-02-16) β 220 ms, 48.1 MBβ
public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length==0) return 0;
int minSoFar = prices[0];
int maxProfitSoFar = 0;
for (int i = 1; i < prices.Length; i++)
{
maxProfitSoFar = Math.Max(maxProfitSoFar, prices[i] - minSoFar);
minSoFar = Math.Min(prices[i], minSoFar);
}
return maxProfitSoFar;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Dynamic Programming | $O(n)$ | $O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.